<?php defined('BASEPATH') OR exit('No direct script access allowed');

class manageCategory extends wsBackend
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('category_model');
    }

    public function index()
    {
        $data = array();
        $filter = array();
        $this->tpl->meta ['title'] = '壁纸分类管理 - ' . $this->config->item('site_name');
        $this->tpl->meta ['description'] = '';
        $this->tpl->meta ['keywords'] = '';
        $this->tpl->page_header = '壁纸分类管理';
        $this->tpl->page_header_ = '';
        $this->tpl->breadcrumbs['壁纸分类管理'] = 'active';

        $data['status'] = array(
            '0' => '启用',
            '1' => '关闭'
        );

        if ($this->input->get('category_name'))
            $filter['name'] = $this->input->get('category_name');
        if (isset($_GET['status']) && array_key_exists($this->input->get('status'), $data['status']))
            $filter['status'] = (int)$this->input->get('status');


        $filter['closure'] = true;
        $filter['show_disabled'] = true;
        $config['uri_segment'] = 4;
        $data['offset'] = $filter['offset'] = $this->uri->segment($config['uri_segment']);
        $config['base_url'] = preg_replace('/' . $this->config->item('url_suffix') . '$/ix', '', admin_url('manageCategory/index'));
        $config['per_page'] = $filter['per_page'] = $this->config->item('items_per_page');

        if (!empty($_GET)) {
            $get_method = '/?' . http_build_query($this->input->get());
            $config['suffix'] = $this->config->item('url_suffix') . $get_method;
            $config['first_url'] = $config['base_url'] . $get_method;
        } else {
            $config['suffix'] = $this->config->item('url_suffix');
        }
        $this->tpl->page_header_ = $config['total_rows'] = $this->category_model->get_categories($filter + array('count' => true));
        $config['use_page_numbers'] = FALSE;
        $this->load->library('pagination');
        $this->pagination->initialize($config);

        $data['pagination'] = $this->pagination->create_links();
        $data['category_list'] = $this->category_model->get_categories($filter);
        $this->tpl->contents [] = $this->tpl->fetch('contents/manageCategory', $data);
        $this->tpl->render();
    }

    public function add()
    {
        $data = array();

        $this->tpl->meta ['title'] = '添加壁纸分类 - ' . $this->config->item('site_name');
        $this->tpl->meta ['description'] = '';
        $this->tpl->meta ['keywords'] = '';
        $this->tpl->page_header = '添加壁纸分类';
        $this->tpl->page_header_ = '';
        $this->tpl->breadcrumbs['Manage Category'] = admin_url('manageCategory');
        $this->tpl->breadcrumbs['添加壁纸分类'] = 'active';
        $data['category'] = false;


        $this->load->library('form_validation');
        $this->form_validation->set_rules('category_name', 'Category Name', 'required|trim');
        //$this->form_validation->set_rules('category_slug', 'Category Slug', 'required|trim');
        if (isset($_POST['category_name']) && empty($_POST['category_slug']))
            $_POST['category_slug'] = build_slug($_POST['category_name'], '-', true);


        if ($this->form_validation->run()) {
            $slug = $this->input->post('category_slug');
            if (!$slug)
                $slug = build_slug($_POST['category_name'], '-', true);
            $slug_check = $this->category_model->get_categoryBySlug($slug);
            if ($slug_check) {
                $this->tpl->error[] = '数据库中已经存在相同的分类目录';
            } else {
                $insert_data = array(
                    'category_name' => $this->input->post('category_name'),
                    'category_slug' => build_slug($this->input->post('category_slug'), '-', true),
                    'category_parent_id' => ($this->input->post('category_parent_id') ? $this->input->post('category_parent_id') : NULL),
                    'category_status' => ($this->input->post('category_status') ? TRUE : FALSE),
                );
                $insert_id = $this->category_model->insert($insert_data);
                if ($insert_id) {
                    $this->session->set_flashdata('SUCCESS', $this->input->post('category_name') . ' - 分类添加成功');
                    redirect(admin_url('manageCategory/add'));
                }
            }
        }

        $data['category_list'] = $this->category_model->get_categoryDropDownTree();

        $this->tpl->contents [] = $this->tpl->fetch('contents/manageCategory_update', $data);
        $this->tpl->render();
    }


    public function edit($id, $offset = '')
    {
        $data = array();
        if (!$id)
            redirect(admin_url('manageCategory'));
        $this->tpl->meta ['title'] = '编辑壁纸分类 - ' . $id . ' ' . $this->config->item('site_name');
        $this->tpl->meta ['description'] = '';
        $this->tpl->meta ['keywords'] = '';
        $this->tpl->page_header = '编辑壁纸分类 - ' . $id;
        $this->tpl->page_header_ = '';
        $this->tpl->breadcrumbs['Manage Category'] = admin_url('manageCategory');
        $this->tpl->breadcrumbs[$id . ' - 编辑壁纸分类'] = 'active';
        $data['category'] = $this->category_model->get_categoryByID($id);
        if (!$data['category']) {
            $this->session->set_flashdata('ERROR', $id . ' - 数据库中不存在类别ID');
            redirect(admin_url('manageCategory'));
        }

        $this->load->library('form_validation');
        $this->form_validation->set_rules('category_name', 'Category Name', 'required|trim');
        //$this->form_validation->set_rules('category_slug', 'Category Slug', 'required|trim');
        if (isset($_POST['category_name']) && empty($_POST['category_slug']))
            $_POST['category_slug'] = build_slug($_POST['category_name'], '-', true);

        if ($this->form_validation->run()) {
            $slug = $this->input->post('category_slug');
            if (!$slug)
                $slug = build_slug($_POST['category_name'], '-', true);
            $slug_check = false;
            if ($slug != $data['category']->category_slug) {
                $slug_check = $this->category_model->get_categoryBySlug($slug);
            }
            if ($slug_check) {
                $this->tpl->error[] = 'Slug Already Exists in the database';
            } else {
                $path_changed = ($data['category']->category_parent_id != $this->input->post('category_parent_id') ? true : false);
                $update_data = array(
                    'category_name' => $this->input->post('category_name'),
                    'category_slug' => build_slug($this->input->post('category_slug'), '-', true),
                    'category_parent_id' => ($this->input->post('category_parent_id') ? $this->input->post('category_parent_id') : NULL),
                    'category_status' => ($this->input->post('category_status') ? TRUE : FALSE),
                );
                $this->category_model->update($update_data, $id, $path_changed);
                $this->session->set_flashdata('SUCCESS', $this->input->post('category_name') . ' - 分类修改成功');
                redirect(admin_url('manageCategory/index/' . $offset));
            }
        }

        $data['category_list'] = $this->category_model->get_categoryDropDownTree($id);

        $this->tpl->contents [] = $this->tpl->fetch('contents/manageCategory_update', $data);
        $this->tpl->render();
    }

    public function delete($id, $offset = '')
    {
        $this->category_model->delete_categoryByID($id);
        $this->session->set_flashdata('SUCCESS', ' Categories ID "' . $id . ' 和子类删除成功');
        redirect(admin_url('manageCategory/index/' . $offset));
    }

    public function delete_bulk($offset = '')
    {
        if (isset($_POST['delete_bulk'])) {
            $cat_ids = $this->input->post('category_id');
            if ($cat_ids) {
                $totalDeleted = $this->category_model->delete_bulkCategory($cat_ids);
                $this->session->set_flashdata('SUCCESS', $totalDeleted . ' 和子类删除成功');
            } else {
                $this->session->set_flashdata('ERROR', '请通过单击复选框选择类别\'s');
            }
            redirect(admin_url('manageCategory/index/' . $offset));
        }
    }

    public function dummy_category()
    {
        $list = '{"3D & Abstract":"","Animals & Birds":{"Cute Animals":"","Tigers":"","Pets":""},"Anime":"","Beach":"","Bikes":"","Brands & Logos":{"Apple":"","Windows":""},"Cars":{"Acura":"","Alfa Romeo":"","Aston Martin":"","Audi":"","Bentley":"","BMW":"","Bugatti":"","Buick":"","Cadillac":"","Chevrolet":"","Citroen":"","Dodge":"","Ferrari":"","Ford":""},"Celebrations":{"New Year":""},"Celebrities":{"Adriana Lima":"","Adrianne Palicki":"","Alicia Silverstone":"","Alison Lohman":"","Alizee":"","Alyssa Milano":"","Amanda Seyfried":"","Amber Heard":"","Amy Adams":"","Ana Ivanovic":"","Angelina Jolie":"","Anna Kournikova":"","Anna Paquin":"","Anne Hathaway":""},"Christmas":"","Creative Graphics":"","Cute":"","Digital Universe":"","Dreamy & Fantasy":"","Dual Monitor":"","Fantasy Girls":"","Flowers":"","Games":"","Inspirational":"","Love":"","Movies":"","TV Shows":"","Nature":"","Others":"","Photography":"","Planes":"","Sports":"","Travel & World":"","Vector & Designs":""}';
        $this->db->truncate('category');
        $this->db->truncate('closures');
        $this->dummy_insert(json_decode($list, true));
        redirect(admin_url('manageCategory'));
    }

    private function dummy_insert($categories, $parentID = NULL)
    {
        foreach ($categories as $name => $sub) {
            $insert_data = array(
                'category_name' => $name,
                'category_slug' => build_slug($name, '-', true),
                'category_parent_id' => $parentID,
                'category_status' => 1,
            );
            $insert_id = $this->category_model->insert($insert_data);
            if (!empty($sub)) {
                $this->dummy_insert($sub, $insert_id);
            }
        }
    }
}
